package chartCraft.tableDesk;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;

import chartCraft.ChartCraftController;
import chartCraft.model.TopModel;
import chartCraft.model.Model.NotifyingMessage;

public class PlayButton extends JButton implements ActionListener, Observer{
	
	private TopModel mTopModel;
	private ChartCraftController mChartCraftController;
	
	private final static String PLAY = "Play";
	private final static String STOP = "Stop";

	public PlayButton(ChartCraftController chartCraftController, TopModel topModel) {
		mChartCraftController = chartCraftController;
		setModel(topModel);
		
		updateMode();
		addActionListener(this);
	}
	
	private void updateMode() {
		boolean isPlaying = mTopModel.isPlaying();
		if (!isPlaying) {
			setText(PLAY);
		} else {
			setText(STOP);
		}
		
		int noOfTime = mTopModel.getNoOfTime();
		if (noOfTime > 1) {
			setEnabled(true);
		} else {
			setEnabled(false);
		}
	}

	public void setModel(TopModel model) {
		mTopModel = model;
		mTopModel.addObserver(this);
	}

	@Override
	public void update(Observable o, Object arg1) {
		if (o == mTopModel) {
			NotifyingMessage msg = (NotifyingMessage) arg1;
			String action = msg.getAction();
			
			if (action == TopModel.PLAY_STATUS_CHANGED) {
				updateMode();
			} else if (action == TopModel.NO_OF_TIME_UPDATED) {
				updateMode();
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (getText() == STOP) {
			mChartCraftController.stopPlaying();
		} else if (getText() == PLAY) {
			mChartCraftController.startPlaying();
		}
	}
}
